<?php
namespace Seller\Controller;
use Think\Exception;
use Think\Log;
use Think\Page;
use Seller\Logic\GoodsLogic;

class IndexController extends BaseController {
    public function index(){
        $this->pushVersion();
        $seller = session('seller');
		$tishi= M('order')->where("store_id = ".STORE_ID." and order_status=0")->select();
        $menu_list = $this->getSellerMenuList($seller['is_admin'],$seller['act_limits']);
        $this->assign('menu_list',$menu_list['seller_menu']);
        $this->assign('seller',$seller);
		$this->assign('tishi',$tishi);
        $this->display();
    }
     /**
     * 检测是否过期
     * */
    public function store_time_end(){
        $store = M('store')->where(['store_id'=>STORE_ID])->find();
        
        $merchant_content_end = M('config')->where(['inc_type'=>'basic','name'=>'merchant_content_end'])->find();
        $merchant_content = M('config')->where(['inc_type'=>'basic','name'=>'merchant_content'])->find();
        $merchant_expiration = M('config')->where(['inc_type'=>'basic','name'=>'merchant_expiration'])->find();
        $time = time();
    
        if($merchant_expiration['value'] == 0){
            return false;
        }
        if($time > $store['store_time_end']){//完全过期
            $day = ceil(($time-$store['store_time_end'])/86400);
            $msg = str_replace('$time',$day,$merchant_content_end['value']);
            echo json_encode(['status'=>1,'msg'=>$msg]);
            exit;
        }else{//还没有过期
            $day = ceil(($store['store_time_end']-$time)/86400);
            if($day<= $merchant_expiration['value']){
                $msg = str_replace('$time',$day,$merchant_content['value']);
                echo json_encode(['status'=>1,'msg'=>$msg]);
                exit;
            }

        }
    }
    public function welcome(){
		$begin = date('Y-m-d 00:00',(time()-30*60*60*24));//30天前
		$end = date('Y-m-d 23:59');
    	$seller = session('seller');
		if($_POST['action']=='dida'){
			$tishi= M('order')->where("stock_up != 2 and store_id = ".STORE_ID." and order_status=0 and add_time>".strtotime($begin)." and add_time<".strtotime($end))->count();//待处理订单
			echo $tishi;
			exit;
		}
		if($_POST['action']=='quxiao'){
			$quxiao= M('order')->where(" store_id = ".STORE_ID." and cancel=0 and add_time>".strtotime($begin)." and add_time<".strtotime($end))->count();//待处理订单
			M('order')->where(" store_id = ".STORE_ID." and cancel=0 and add_time>".strtotime($begin)." and add_time<".strtotime($end))->save(['cancel'=>1]);
		    echo $quxiao;
			exit;
		}
    	$count['handle_order'] = M('order')->where("store_id = ".STORE_ID." and order_status=0 and add_time>".strtotime($begin)." and add_time<".strtotime($end))->count();//待处理订单
    	$order_list =  M('order')->field('order_id,order_status')->where("store_id = ".STORE_ID)->select();//总订单统计
    	// $count['wait_shipping'] = $count['wait_pay'] = $count['wait_confirm'] = $count['refund_pay'] = 0;
    	//$count['refund_goods'] = $count['part_shipping'] = $count['order_sum'] = 0;
    	$count['refund_pay'] = M('return_goods')->where("getorder = 0 and store_id = ".STORE_ID.' and status <> 3')->count();
    	$count['refund_goods'] = M('return_goods')->where("store_id = ".STORE_ID." and type=1")->count();
		$count['heji_price'] = M('order')->where("store_id = ".STORE_ID." and order_status in(0,1,2,4)")->sum(order_amount);
    	if($order_list){
    		$count['order_sum'] = count($order_list);
    		foreach ($order_list as $v){
				if($v['order_status'] ==3 || $v['order_status'] ==5){
    				$count['wait_confirm']++;
    			}
				if($v['order_status'] == 1){
    				$count['part_shipping']++;
    			}
				if($v['order_status'] == 2){
    				$count['wancheng']++;
    			}
    		}
    	}
    	
    	$store_goods = M('goods a')
		->field('a.*,(select count(*) from ty_spec_goods_price b where b.goods_id=a.goods_id and b.store_count<=5) as kucun_lost')
		->where(array('a.store_id'=>STORE_ID))->select();
		$count['spec'] =  M('spec_goods_price s')->join('ty_goods g on g.goods_id = s.goods_id')
    	->where("g.store_id=".STORE_ID)
    	->count();//商品总数
    	$count['pass_goods_spec'] =  M('spec_goods_price s')->join('ty_goods g on g.goods_id = s.goods_id')
    	->where("g.store_id=".STORE_ID.' and goods_state = 1 and g.is_on_sale = 1 and g.is_delete = 0')
    	->count();//商品总数
    	$count['goods_sum'] = $count['pass_goods'] = $count['warning_goods'] = $count['weigui'] = 0;
    	$count['prom_goods'] = $count['off_sale_goods']  = $count['below_goods'] = $count['verify_goods'] = 0;
		$count['kucuns'] ='';
    	if($store_goods){
    		$count['goods_sum'] = count($store_goods);//出售中商品总数
    		foreach ($store_goods as $k=>$val){ 
    			if($val['goods_state'] == 0 ){
    				$count['verify_goods']++;
    			}
				if($val['goods_state'] == 1 and $val['is_delete'] == 0 and $val['is_on_sale'] == 1){
    				$count['pass_goods']++;
    			}
				if($val['goods_state'] == 2){
    				$count['below_goods']++;
    			}
				if($val['goods_state'] == 0 and $val['is_delete'] == 0){
    				$count['off_sale_goods']++;
    			}
				if($val['goods_state'] == 3){
					$count['weigui']++;
				}
				if($val['prom_id'] >0){
    				$count['prom_goods']++;
    			}
				if($val['kucun_lost']>0){
					$count['kucuns'].=$val['goods_id'].',';
    				$count['warning_goods']++;
    			}
				
    		}
    	}
		$count['kucuns']=\rtrim($count['kucuns'],',');
		
  //   	echo '<span style="color:red">系统升级中。。。请各位商家忽略此页，其他功能正常使用。</span>';
		// echo $count['kucuns'];exit;
		
    	$count['order_list'] = count($order_list);//订单总数
    	$users = M('users')->where(array('user_id'=>$seller['user_id']))->find();
    	$seller['user_name'] = empty($users['email']) ? $users['mobile'] : $users['email'];
    	//今天销售总额
    	$today = strtotime(date("Y/m/d"));
    	$count['total_amount'] = M('order')->where("store_id = ".STORE_ID." and add_time>$today and order_status in(0,1,2,4)")->sum('total_amount');
    	// $count['comment'] = M('comment')->where("is_show=0 and store_id=".STORE_ID)->count();//最新评论
    	// $count['consult'] = M('goods_consult')->where("is_show=0 and store_id=".STORE_ID)->count();//最新咨询
    	$this->assign('count',$count);

        $store = M('store a')
            ->field('a.*,u.mobile as mobile')
            ->join('ty_users u on u.user_id = a.user_id','LEFT')
            ->where(array('a.store_id'=>STORE_ID))
            ->find();
    	if($store['store_logo']!='/Public/images/mylogo.jpg'){
            $store['store_logo'] = !file_get_contents($_SERVER['SERVER_NAME'].'/'.$store['store_logo']) ? C('MYOSS')['url'].$store['store_logo'] : $store['store_logo'] ;
        }
    	$this->assign('store',$store);
    	$this->assign('seller',$seller);
        $this->display();
    }
    
    /**
     * 商家查看消息
     */
    public function store_msg(){
        $where = "store_id=".STORE_ID;
        $count = M('store_msg')->where($where)->count();
        $Page  = new Page($count,10);
        $show = $Page->show();
        
    	$msg_list = M('store_msg')->where($where)->order('sm_id DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
    	$this->assign('msg_list',$msg_list);
        $this->assign('page',$show);// 赋值分页输出
    	$this->display();
    }
    /**
     * 删除操作
     */
    public function del_store_msg()
    {        
        $sm_id = I('sm_id',0);
        $where = "sm_id in($sm_id) and store_id=".STORE_ID;
        M('store_msg')->where($where)->delete();
        $this->success('操作成功!');
    }
    /**
     * 消息批量操作
     */
    public function store_msg_batch()
    {        
        $action = I('action',0);
        $sm_id = I('sm_id');
        
        // 如果是标记已读
        if($action == 'del' && !empty($sm_id))
        {
            $where = "sm_id in(".  implode(',',$sm_id).") and store_id=".STORE_ID;
            M('store_msg')->where($where)->delete();
        }
        // 如果是标记已读
        if($action == 'open' && !empty($sm_id))
        {
            $where = "sm_id in(".  implode(',',$sm_id).") and store_id=".STORE_ID;
            M('store_msg')->where($where)->save(array('open'=>1));       
        }
        $this->success('操作成功!');
    }    
    
    /**
     *  添加修改客服
     */
    public function store_service(){
        
        // post提交
        if(IS_POST)
        {
            $pre = I('pre');
            $after = I('after');
            $working_time = I('working_time');
            foreach($pre as $k => $v){
                if(empty($v['name']) || empty($v['account']))
                    unset ($pre[$k]);
            }
            foreach($after as $k => $v){
                if(empty($v['name']) || empty($v['account']))
                    unset ($after[$k]);
            }
            $data = array(
                'store_presales'=>serialize($pre),
                'store_aftersales'=>serialize($after),
                'store_workingtime'=>$working_time,
            );            
            M('store')->where("store_id = ".STORE_ID)->save($data);
            $this->success('修改成功');
            exit();
        }
        //
        $store = M('store')->where("store_id = ".STORE_ID)->find();
        $store['store_presales']    = unserialize($store['store_presales']);
        $store['store_aftersales']  = unserialize($store['store_aftersales']);        
        $this->assign('store',$store);        
    	$this->display();
    }
    
    public function pushVersion()
    {            
        if(!empty($_SESSION['isset_push']))
            return false;    
        $_SESSION['isset_push'] = 1;    
        error_reporting(0);//关闭所有错误报告
        $app_path = dirname($_SERVER['SCRIPT_FILENAME']).'/';
        $version_txt_path = $app_path.'/Application/Admin/Conf/version.txt';
        $curent_version = file_get_contents($version_txt_path);

        $vaules = array(            
                'domain'=>$_SERVER['SERVER_NAME'], 
                'last_domain'=>$_SERVER['SERVER_NAME'], 
                'key_num'=>$curent_version, 
                'install_time'=>INSTALL_DATE, 
                'cpu'=>'0001',
                'mac'=>'0002',
                'serial_number'=>SERIALNUMBER,
         );     
         $url = "http://service.tp".'-'."shop".'.'."cn/index.php?m=Home&c=Index&a=user_push&".http_build_query($vaules);
         stream_context_set_default(array('http' => array('timeout' => 3)));
         file_get_contents($url);         
    }
    
    /**
     * ajax 修改指定表数据字段  一般修改状态 比如 是否推荐 是否开启 等 图标切换的
     * table,id_name,id_value,field,value   shadow
     */
    public function changeTableVal(){

            $table = I('table'); // 表名
            $id_name = I('id_name'); // 表主键id名
            $id_value = I('id_value'); // 表主键id值
            $field  = I('field'); // 修改哪个字段
            $value  = I('value'); // 修改字段值
			$ids=M($table)->where("`$id_name` = '$id_value' and store_id = ".STORE_ID)->getField('goods_id');
				M($table)->where("`$id_name` = '$id_value' and store_id = ".STORE_ID)->save(array($field=>$value)); //更新数据
			cart_price($ids); //更新购物车
    }
    
        /**
     * ajax 修改指定表数据字段  一般修改状态 比如 是否推荐 是否开启 等 图标切换的
     * table,id_name,id_value,field,value   shadow
     */
    public function changeTableVala(){
            
           
            $table = I('table'); // 表名
            $id_name = I('id_name'); // 表主键id名
            $id_value = I('id_value'); // 表主键id值
            $field  = I('field'); // 修改哪个字段
            $value  = I('value'); // 修改字段值
			M($table)->where("`$id_name` = '$id_value' and store_id = ".STORE_ID)->save(array($field=>$value)); //更新数据

			
    }
    public function changebiaoqian(){
        // if($_POST){
        //     $table = I('table'); // 表名
        //     $id_name = I('id_name'); // 表主键id名
        //     $order_id = I('order_id'); // 表主键id值
        //     $field  = I('field'); // 修改哪个字段
        //     $value  = I('value'); // 修改字段值

        //     $order = M('order')->where('order_id='.$order_id.' and store_id = '.STORE_ID.' and order_status =0 ')->find();
        //     M()->startTrans();
        //     try {
        //         if($order && $value<=300) {
        //             M($table)->where("$id_name = $order_id and store_id = " . STORE_ID)->save(array($field => $value)); // 根据条件保存修改的数据
        //             M('order_jian')->where('order_id=' . $order_id)->delete();//删除出入库重写写入记录
        //             for ($i = 1; $i <= (int)$value; $i++) {
        //                 M('order_jian')->add([
        //                     "order_id" => $order_id,
        //                     "ruku_num" => $i,
        //                     "chuku_num" => $i
        //                 ]);
        //             }
        //         }
        //         M()->commit();
        //     }catch (\Exception $e){
        //         M()->rollback();
        //         Log::record($e->getMessage(),'DEBUG');
        //     }

        // }
		
        if($_POST){
            $table = I('table'); // 表名
            $id_name = I('id_name'); // 表主键id名
            $order_id = I('order_id'); // 表主键id值
            $field  = I('field'); // 修改哪个字段
            $value  = I('value'); // 修改字段值
            
            if($table=="store"){
                 M($table)->where("$id_name = $order_id and store_id = ".STORE_ID)->save(array($field=>$value));
            }else{
                if($field == 'jian_count' && $value>150){
                   echo json_encode(['status'=>0,'msg'=>'单个订单标签数上限150个，请包装尽量捆绑一起。']);exit;
                }
                $sql = M($table)->where("$id_name = $order_id and store_id = " . STORE_ID)->save(array($field => $value)); // 根据条件保存修改的数据
                $order = M('order')->where('order_id='.$order_id.' and store_id = '.STORE_ID.' and order_status =0')->find();
                if($order && $value<=150) {
                    M('order_jian')->where('order_id=' . $order_id)->delete();//删除出入库重写写入记录
                    for ($i = 1; $i <= (int)$value; $i++) {
                        M('order_jian')->add([
                            "order_id" => $order_id,
                            "ruku_num" => $i,
                            "chuku_num" => $i,
    						"zruku_num"=>$i,
    						"zchuku_num"=>$i
                        ]);
                    }
                }
            }
            echo json_encode(['status'=>1,'msg'=>'更新成功']);exit;
        }
    }
    // 20181020 增加相片排序指定表数据字段 亮 START
    public function changeTableValss(){
        $table = I('table'); // 表名
        $id_name = I('id_name'); // 表主键id名
        $id_value = I('id_value'); // 表主键id值
        $field  = I('field'); // 修改哪个字段
        $value  = I('value'); // 修改字段值
        if($table =='spec_item' && $field == 'item'){
             //php检测非法字符的一种方法
            $illegal_character="['!`~\\\\^=\$\:;<>\]\[{}]";
            // $illegal_character="#['!`~\/\\\^=\$\:;<>\]\[{}]#";
    
            if(preg_match($illegal_character,$value)){
                $return_arr = array(
                    'status' => -1,
                    'msg'   => '规格存在非法符号',
                    'data'  =>'',
                );
                exit(json_encode($return_arr));
            }
        }
        $sql= M($table)->where("$id_name = $id_value and store_id = ".STORE_ID)->save(array($field=>$value)); // 根据条件保存修改的数据
        if($sql){
            $return_arr = array(
                'status' => 1,
                'msg'   => '保存成功',
                'data'  =>'',
            );
            exit(json_encode($return_arr));
        }else{
            $return_arr = array(
                'status' => -1,
                'msg'   => '保存失败',
                'data'  =>'',
            );
            exit(json_encode($return_arr));
        }
    }
    // 20181020 增加相片排序指定表数据字段 亮 END
    
    private function _getSellerFunctionList($menu_list) {
    	$format_menu = array();
    	foreach ($menu_list as $key => $menu_value) {
    		foreach ($menu_value['child'] as $submenu_value) {
    			$format_menu[$submenu_value['act']] = array(
    					'model' => $key,
    					'model_name' => $menu_value['name'],
    					'name' => $submenu_value['name'],
    					'act' => $submenu_value['act'],
    					'op' => $submenu_value['op'],
    			);
    		}
    	}
    	return $format_menu;
    }
    
    protected function getSellerMenuList($is_admin, $limits) {
    	$seller_menu = array();
    	/*
    	if (intval($is_admin) !== 1) {
    		$menu_list = getMenuList();
    		foreach ($menu_list as $key => $value) {
    			foreach ($value['child'] as $child_key => $child_value) {
    				if (!in_array($child_value['act'], $limits)) {
    					unset($menu_list[$key]['child'][$child_key]);
    				}
    			}
    
    			if(count($menu_list[$key]['child']) > 0) {
    				$seller_menu[$key] = $menu_list[$key];
    			}
    		}
    	} else {
    		$seller_menu = getMenuList();
    	}
    	*/
    	$unusualCount = M('order')->where('((ruku_count>0 and ruku_count != jian_count and order_status = 1) OR (order_status = 1 and pda_qdzt=1) ) and store_id='.STORE_ID
        )->count();
        $fix_count = M('fix_goods')->where("store_id = ".STORE_ID." and is_receive=0")->count();
    	$seller_menu = getMenuList($unusualCount,$fix_count);
    	$seller_function_list = $this->_getSellerFunctionList($seller_menu);
        //查询商家是否绑定了广西
        $guangxi = M('sync_account')->where(['store_id'=>STORE_ID,'tag'=>'guangxi'])->count();
        if($guangxi != 0){
            //$seller_menu['order']['child'][] = array('name' => '广西订单', 'act'=>'syncOrderList?tag=guangxi', 'op'=>'Order');
        }
    	return array('seller_menu' => $seller_menu, 'seller_function_list' => $seller_function_list);
    }
    
    private function _getCurrentMenu($seller_function_list) {
    	$current_menu = $seller_function_list[$_GET['act']];
    	if(empty($current_menu)) {
    		$current_menu = array(
    				'model' => 'index',
    				'model_name' => '首页'
    		);
    	}
    	return $current_menu;
    }
    
    /*
     * 获取商品分类
     */
    public function get_category(){
        $parent_id = I('get.parent_id',0); // 商品分类 父id  
        empty($parent_id) && exit('');
        $list = M('goods_category')->where(array('parent_id'=>$parent_id))->select();
        // 店铺id
         $store_id = session('store_id');
        //如果店铺登录了
        if($store_id)
        {
            $store = M('store')->where("store_id = $store_id")->find();
               
            if($store['bind_all_gc'] == 0)
            {                            
                $class_id1 = M('store_bind_class')->where("store_id = $store_id and state = 1")->getField('class_1',true);
                $class_id2 = M('store_bind_class')->where("store_id = $store_id and state = 1")->getField('class_2',true);
                $class_id3 = M('store_bind_class')->where("store_id = $store_id and state = 1")->getField('class_3',true);
                $class_id = array_merge($class_id1,$class_id2,$class_id3);
                $class_id = array_unique($class_id);          
            }
        }
     
        foreach($list as $k => $v)
        {
            // 如果是某个店铺登录的, 那么这个店铺只能看到自己申请的分类,其余的看不到
/*             if($class_id && !in_array($v['id'],$class_id))
                continue; */
            $html .= "<option value='{$v['id']}' rel='{$v['commission']}'>{$v['name']}</option>";
        }
            
        exit($html);
    }  
    
    /**
    *获取商品分类下面的品牌
    **/
    public function get_brandList(){
        $parent_id = I('get.parent_id',0); // 商品分类 父id  
        $key = I('get.brand_key',0); // 商品分类 父id  
        $GoodsLogic = new GoodsLogic();
     
        $brandList = $GoodsLogic->getSortBrands($parent_id,$key);
        $arr = [];
        $arr['code'] = 1;
        $arr['data'] = $brandList;
        $arr['Ncount'] = count($brandList);
        echo json_encode($arr);	
    }

}